# -*- encoding: utf-8 -*-
"""
PyCharm emailNote  邮件提醒模块
2022年09月03日
by littlefean
"""

import os
import pathlib
from typing import *

import yagmail
from jsonDBList import JsonDBList
from jsonDBDict import JsonDBDict
from pyDBSet import PyDBSet
from datetime import datetime
from time import sleep

psw = pathlib.Path("emailPassword.txt").read_text().strip()
email = yagmail.SMTP(
    host='smtp.qq.com',
    user="2385190373@qq.com",
    password=psw,
    smtp_ssl=True
)


def listWeek(chineseList) -> List[int]:
    res = []
    for item in chineseList:
        if item == "周一":
            res.append(1)
        elif item == "周三":
            res.append(3)
        elif item == "周二":
            res.append(2)
        elif item == "周五":
            res.append(5)
        elif item == "周六":
            res.append(6)
        elif item == "周四":
            res.append(4)
        elif item == "周日":
            res.append(7)
    return res


def run():
    """
    这个函数要是一个异步函数，不能在这里阻塞
    :return:
    """
    while True:
        sleep(3)
        pyLog = PyDBSet("emailSendLog")

        d = datetime.now()

        # 不停的检测所有的用户，检测所有的用户中是否有一个用户需要发送邮件了
        for fileName in os.listdir("myDB/jsonDB/"):
            if fileName.endswith("WeekEvent.json"):
                userName = fileName.replace("WeekEvent.json", "")
                # 获取这个人的所有周常事件
                obj = JsonDBList(fileName.replace(".json", ""))
                # 获取这个人的邮箱
                userEmail = JsonDBDict("users")[userName]["email"]
                for event in obj.contentArr:
                    # 开始检测这个是否是需要发送的
                    if event["alarm"]:
                        # 检测时间是否符合
                        h, m = map(int, event["startTime"].split(":"))
                        if d.isoweekday() in listWeek(event["weekList"]) and \
                                (d.hour > h or (d.hour == h and d.minute >= m)):
                            # 时间成立
                            # 检测今天的提醒是否已经发过了
                            todayStr = f"{userName}{event['startTime']}{event['title']}-{d.month}.{d.day}"
                            if todayStr in pyLog:
                                # 已经发送了
                                continue
                            # 开始发送
                            content = f"{event['title']}时间到了，开始时间是{event['startTime']}"
                            try:
                                email.send(userEmail, f"时间碎片周常事件提醒：{event['title']}", content)
                            except Exception as e:
                                print(e)
                            # 计入log
                            pyLog.add(todayStr)
                            pyLog.save()


def main():
    run()
    return None


if __name__ == "__main__":
    main()
